<template>
  <div class="upload">
    <div class="file-list">
      <div
        class="file-item"
        v-for="item in fileList"
        :key="item.url"
        :style="{display:type != 'text'?'':'none'}"
      >
        <el-image
          class="upload-image"
          :src="item.url"
          :preview-src-list="disabled ? [item.url] : []"
        ></el-image>
        <div class="upload-actions" v-if="type != 'text'">
          <i class="el-icon-zoom-in" @click="handlePreview(item)"></i>
          <i class="el-icon-delete" v-if="!disabled" @click="handleRemove(item, fileList)"></i>
        </div>
      </div>
      <el-upload
        class="upload-item"
        :style="type != 'text'?'width: 100px; height: 100px':''"
        :class="((fileList.length < limit && !disabled )||type == 'text')?'':'uploadNone'"
        action
        :disabled="progressPercent>0"
        :list-type="type"
        :multiple="multiple"
        :show-file-list="type == 'text'"
        :limit="limit"
        :data="params"
        :on-exceed="onExceed"
        :on-success="handleUploadSuccess"
        :on-error="onError"
        :on-remove="onRemove"
        :accept="thumbnail?null:accept"
        :http-request="httpRequest"
        :before-upload="onBeforeUpload"
        :file-list="fileList"
      >
        <el-progress
          :type="type=='text'?'line':'circle'"
          :percentage="progressPercent"
          :class="{'progress-circle':type!='text'}"
          :text-inside="false"
          :width="type!='text'?50:200"
          :style="type=='text'?'width: 200px;height:40px':''"
          :stroke-width="6"
          v-if="progressPercent"
        ></el-progress>
        <el-button size="small" style="transform: scale(0.7)" v-else type="primary">点击上传</el-button>
      </el-upload>
    </div>
    <!-- <span class="accept">支持{{ accept }}格式</span> -->

    <el-dialog :visible.sync="visible" append-to-body>
      <div class="preview">
        <img width="500px" :src="dialogImageUrl" alt />
      </div>
    </el-dialog>
  </div>
</template>
<script>
import request from "@/utils/request";

import { getToken } from "@/utils/auth.js";
import { apiCommonUpload } from "@/api/login";
export default {
  components: {},
  props: {
    disabled: {
      type: Boolean,
      default: false
    },
    limit: {
      //最大允许上传个数
      type: Number,
      default: 1
    },
    params: {
      //上传时附带的额外参数
      type: Object,
      default: () => {}
    },
    headers: {
      type: Object,
      default: () => {
        return {
          RSnetToken: getToken()
        };
      }
    },
    thumbnail: {
      type: Boolean,
      default: false
    },
    multiple: {
      //是否支持多选文件
      type: Boolean,
      default: false
    },
    files: {
      //已上传文件列表
      type: Array,
      default: () => []
    },
    type: {
      //文件列表的类型
      type: String,
      default: "picture-card"
    },
    accept: {
      type: String,
      default: ".jpg,.png,.jpeg"
    }
  },
  data() {
    return {
      action: process.env.VUE_APP_BASE_API + "/common/upload",
      dialogImageUrl: "",
      visible: false,
      progressPercent: 0
    };
  },
  computed: {
    fileList() {
      return this.files.map(item => {
        return { url: item, name: this.getChineseFilename(item) };
      });
    }
  },
  mounted() {},
  methods: {
    httpRequest(e) {
      // 上传新文件时，将进度条值置为零
      this.progressPercent = 1;
      const formData = new FormData();
      formData.append("file", e.file);
      formData.append("fileName", e.name);
      return request({
        url: `/common/upload`,
        method: "post",
        data: formData,
        headers: { "Content-Type": "multipart/form-data" },
        onUploadProgress: progressEvent => {
          // progressEvent.loaded:已上传文件大小
          // progressEvent.total:被上传文件的总大小
          let  progressPercent= parseInt(
            (progressEvent.loaded / progressEvent.total) * 100
          );
          this.progressPercent = progressPercent>99?99:progressPercent
          console.info(progressEvent.loaded);
          console.info(progressEvent.total);
        }
      });
    },

    // 手动实现上传接口
    onHttpRequest(e) {
      const formData = new FormData();
      formData.append("file", e.file);
      formData.append("fileName", e.name);
      return apiCommonUpload(formData);
    },

    // 上传成功回调
    handleUploadSuccess(response, file, fileList) {
      if (response.code == "SUCCESS") {
        this.progressPercent = 100;

        setTimeout(() => {
          this.progressPercent = 0;
        }, 1000);
        let ele = {
          url: response.data.url,
          name: response.data.originalFilename
        };
        this.$set(this.fileList, this.fileList.length, ele);
        this.$emit("upload", { files: this.fileList });
      } else {
        this.$message({
          type: "warning",
          message: response.msg
        });
      }
    },
    // type:card手动删除图片
    handleRemove(file) {
      const files = this.fileList.filter(item => item.url != file.url);
      this.$emit("upload", { files: files });
    },
    // type:text删除图片回调
    onRemove(file, fileList) {
      const files = fileList.map(item => {
        return {
          url: item.response.data.url,
          name: item.name
        };
      });
      this.$emit("upload", { files: files });
    },
    // 图片预览
    handlePreview(file) {
      this.dialogImageUrl = file.url;
      this.visible = true;
    },
    // 上传前大小格式验证
    onBeforeUpload(file) {
      const isLt10M = file.size / 1024 / 1024 < 10;
      if (!isLt10M) {
        this.$message.error("上传图片大小不能超过 10MB!");
      }
      return isLt10M;
    },
    // 超出限制
    onExceed() {
      this.$message.warning(`最多可上传${this.limit}个文件`);
    },
    // 上传失败
    onError(err, file, fileList) {
      this.$message({
        type: "warning",
        message: "资源上传失败"
      });
    },
    // 获取文件名
    getChineseFilename(url) {
      // 使用URL对象来解析URL
      const parsedUrl = new URL(url);
      // 获取路径名，它将包含文件名
      const pathname = parsedUrl.pathname;
      // 获取最后一个'/'字符之后的部分，即文件名
      const filename = pathname.substring(pathname.lastIndexOf("/") + 1);
      // 返回文件名
      return decodeURIComponent(filename);
    }
  }
};
</script>
<style scoped lang="scss">
::v-deep .el-upload-list__item.is-ready {
  //因为此饿了么组件图片上传的时候会产生一个类,将其隐藏就可以解决上传图片完成后闪动的问题
  opacity: 0;
}
::v-deep .el-upload--picture-card {
  width: 100px !important;
  height: 100px !important;
  line-height: 100px !important;
}
.upload {
  display: flex;
  flex-wrap: wrap;
}
.file-list {
  display: flex;
  flex-wrap: wrap;
}
.file-item {
  width: 100px;
  height: 100px;
  position: relative;
  border-radius: 5px;
  overflow: hidden;
  margin: 0 10px 10px 0;
  &:hover {
    .upload-actions {
      display: flex;
    }
  }

  .upload-image {
    width: 100%;
    height: 100%;
  }
  .upload-actions {
    display: none;
    width: 100%;
    height: 100%;
    position: absolute;
    left: 0;
    top: 0;
    background-color: rgba($color: #000000, $alpha: 0.4);
    align-items: center;
    justify-content: space-around;
    i {
      font-size: 24px;
      color: #fff;
      cursor: pointer;
    }
  }
}
.preview {
  display: flex;
  align-items: center;
  justify-content: center;
}
::v-deep .el-upload-list__item-name {
  width: 300px;
}
.uploadNone {
  display: none;
}
.upload-item {
  position: relative;
}
.accept {
  display: block;
  height: 16px;
  line-height: 16px;
  position: absolute;
  left: 0;
  top: 100%;
  font-size: 10px;
}
.progress-circle {
  position: absolute;
  left: 50%;
  top: 50%;
  transform: translate(-50%, -50%);
}
</style>
